import React, { useState, useEffect, useRef, useCallback } from 'react';
import {
  Table,
  Button,
  Tag,
  message,
  Space,
  Card,
  Typography,
  Row,
  Col,
} from 'antd';
import { InfoCircleOutlined, RightOutlined } from '@ant-design/icons';
import * as XLSX from 'xlsx';
import { setStrategyType, getStrategyType  } from '@/utils/keyTypeStore'
const { Title, Text } = Typography;

const generateMockBook = nextId => {
  const realTitles = [
    '百年孤独',
    '1984',
    '动物农场',
    '小王子',
    '围城',
    '活着',
    '三体',
    '人类简史',
    '情商',
    '影响力',
    '乌合之众',
    '君主论',
    '资治通鉴',
    '红楼梦',
    '西游记',
    '水浒传',
    '三国演义',
    '呐喊',
    '朝花夕拾',
    '边城',
  ];
  const realAuthors = [
    '加西亚·马尔克斯',
    '乔治·奥威尔',
    '安托万·德·圣-埃克苏佩里',
    '钱钟书',
    '余华',
    '刘慈欣',
    '尤瓦尔·赫拉利',
    '丹尼尔·戈尔曼',
    '古斯塔夫·勒庞',
    '尼科洛·马基雅维利',
    '司马光',
    '曹雪芹',
    '吴承恩',
    '施耐庵',
    '罗贯中',
    '鲁迅',
    '沈从文',
  ];
  const realPublishers = [
    '新经典文化',
    '上海译文出版社',
    '人民文学出版社',
    '北京十月文艺出版社',
    '重庆出版社',
    '中信出版集团',
    '浙江人民出版社',
    '商务印书馆',
    '译林出版社',
    '南海出版公司',
  ];
  const descriptions = [
    '本书详细介绍了相关技术原理与实践。',
    '适合初学者和进阶开发者阅读。',
    '内容涵盖理论与实战案例。',
    '帮助读者快速掌握核心知识。',
  ];
  return {
    id: nextId,
    title: realTitles[Math.floor(Math.random() * realTitles.length)],
    author: realAuthors[Math.floor(Math.random() * realAuthors.length)],
    status: ['在架', '借出', '维护'][Math.floor(Math.random() * 3)],
    expanded: false,
    isbn: '978' + Math.floor(1000000000 + Math.random() * 9000000000),
    publisher:
      realPublishers[Math.floor(Math.random() * realPublishers.length)],
    publishDate: `202${Math.floor(Math.random() * 4 + 1)}-0${Math.floor(
      Math.random() * 9 + 1
    )}-15`,
    description: descriptions[Math.floor(Math.random() * descriptions.length)],
    price: (Math.random() * 100 + 20).toFixed(2),
    rating: (Math.random() * 2 + 3).toFixed(1),
  };
};

const domTrackStats = {
  created: 0,
  reused: 0,
  destroyed: 0,
  reset() {
    this.created = 0;
    this.reused = 0;
    this.destroyed = 0;
  },
};

const DomTracker = ({ id, children }) => {
  const ref = useRef(null);

  useEffect(() => {
    domTrackStats.created++;
    return () => {
      domTrackStats.destroyed++;
    };
  }, []);

  useEffect(() => {}, [id]);

  return <span ref={ref}>{children}</span>;
};

const BookList = () => {
  const [books, setBooks] = useState([]);
  const [academicBooks, setAcademicBooks] = useState([]);
  const nextIdRef = useRef(1);
  const [renderTime, setRenderTime] = useState(null);


  const [keyType, setKeyType] = useState(getStrategyType());
  const [showAcademicTestList, setShowAcademicTestList] = useState(false);
  const [currentDomTrackStats, setCurrentDomTrackStats] = useState({
    created: 0,
    reused: 0,
    destroyed: 0,
  });



  const handleToggleType = (value) => {
    message.success({
      content: `已切换到${value}`,
    });
    setKeyType(value)
    setStrategyType(value)
  }
  const reuseRate = useCallback(() => {
    const N = academicBooks.length;
    if (N === 0) return '0.00';

    const reusedCount = N - currentDomTrackStats.destroyed;

    return (reusedCount >= 0 && N > 0 ? (reusedCount / N) * 100 : 0).toFixed(2);
  }, [academicBooks.length, currentDomTrackStats.destroyed]);

  useEffect(() => {
    
    generateBooks(10);

  }, []);

  const getStatusType = status => {
    switch (status) {
      case '在架':
        return 'success';
      case '借出':
        return 'warning';
      case '维护':
        return 'error';
      default:
        return 'default';
    }
  };

  const toggleExpand = useCallback(recordId => {
    setBooks(prevBooks =>
      prevBooks.map(book =>
        book.id === recordId ? { ...book, expanded: !book.expanded } : book
      )
    );
  }, []);

  const viewBookDetail = useCallback(bookId => {
    message.info(`查看图书详情: ${bookId}`);
  }, []);

  const editBook = useCallback(() => {
    message.info('编辑功能开发中...');
  }, []);

  const preciseMeasure = useCallback((desc = '渲染完成') => {
    performance.clearMarks();
    performance.clearMeasures();
    performance.mark('start-render');

    requestAnimationFrame(() => {
      performance.mark('end-render');
      performance.measure('render', 'start-render', 'end-render');
      const measures = performance.getEntriesByName('render');
      if (measures.length > 0) {
        setRenderTime(measures[0].duration.toFixed(2));
      }
    });
  }, []);

  const generateBooks = useCallback((count = 10) => {
    nextIdRef.current = 1;
    const newBooks = Array.from({ length: count }, () =>
      generateMockBook(nextIdRef.current++)
    );
    setBooks(newBooks);
  }, []);

  const bulkGenerate = useCallback(() => {
    nextIdRef.current = 1;
    const newBooks = [];
    for (let i = 0; i < 1000; i++) {
      newBooks.push(generateMockBook(nextIdRef.current++));
    }
    setBooks(newBooks);
    preciseMeasure('批量生成1000项');
  }, [preciseMeasure]);

  const addItem = useCallback(() => {
    if (books.length >= 2000) return;
    setBooks(prevBooks => [
      ...prevBooks,
      generateMockBook(nextIdRef.current++),
    ]);
    preciseMeasure('添加项');
  }, [books.length, preciseMeasure]);

  const removeItem = useCallback(() => {
    if (books.length <= 1) return;
    setBooks(prevBooks => {
      const newBooks = [...prevBooks];
      newBooks.splice(Math.floor(Math.random() * newBooks.length), 1);
      return newBooks;
    });
    preciseMeasure('删除项');
  }, [books.length, preciseMeasure]);

  const shuffleList = useCallback(() => {
    const start = performance.now();
    setBooks(prevBooks => {
      const newBooks = [...prevBooks];
      for (let i = newBooks.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newBooks[i], newBooks[j]] = [newBooks[j], newBooks[i]];
      }
      return newBooks;
    });

    requestAnimationFrame(() => {
      const end = performance.now();
      setRenderTime((end - start).toFixed(2));
    });
  }, []);

  const getKey = useCallback(
    (record, index) => {
      if (keyType === 'id') {
        return record.id;
      } else if (keyType === 'index') {
        return index;
      } else {
        return `no-key-${index}`;
      }
    },
    [keyType]
  );

  const insertRandomBook = useCallback(() => {
    setBooks(prevBooks => {
      const newBooks = [...prevBooks];
      const idx = Math.floor(Math.random() * (newBooks.length + 1));
      newBooks.splice(idx, 0, generateMockBook(nextIdRef.current++));
      return newBooks;
    });
  }, []);

  const deleteRandomBook = useCallback(() => {
    if (books.length === 0) return;
    setBooks(prevBooks => {
      const newBooks = [...prevBooks];
      const idx = Math.floor(Math.random() * newBooks.length);
      newBooks.splice(idx, 1);
      return newBooks;
    });
  }, [books.length]);

  const replaceAllBooks = useCallback(() => {
    const len = books.length;
    nextIdRef.current = 1;
    setBooks(
      Array.from({ length: len }, () => generateMockBook(nextIdRef.current++))
    );
  }, [books.length]);

  const appendToEnd = useCallback(() => {
    setBooks(prevBooks => [
      ...prevBooks,
      generateMockBook(nextIdRef.current++),
    ]);
  }, []);

  const stepInsert = useCallback(() => {
    setBooks(prevBooks => {
      const newBooks = [...prevBooks];
      for (let i = 0; i < 10; i++) {
        newBooks.splice(i * 2, 0, generateMockBook(nextIdRef.current++));
      }
      return newBooks;
    });
  }, []);

  const insertToMiddle = useCallback(() => {
    setBooks(prevBooks => {
      const newBooks = [...prevBooks];
      const mid = Math.floor(newBooks.length / 2);
      newBooks.splice(mid, 0, generateMockBook(nextIdRef.current++));
      return newBooks;
    });
  }, []);

  const partialUpdate = useCallback(() => {
    if (books.length === 0) return;
    setBooks(prevBooks => {
      const newBooks = [...prevBooks];
      for (let i = 0; i < 10 && newBooks.length > 0; i++) {
        const idx = Math.floor(Math.random() * newBooks.length);
        newBooks[idx] = {
          ...newBooks[idx],
          title: newBooks[idx].title + '_更新',
        };
      }
      return newBooks;
    });
  }, [books.length]);

  const sleep = useCallback(ms => {
    return new Promise(resolve => setTimeout(resolve, ms));
  }, []);

  const generateAcademicBooks = useCallback(count => {
    nextIdRef.current = 1;
    setAcademicBooks(
      Array.from({ length: count }, () => generateMockBook(nextIdRef.current++))
    );
  }, []);

  const shuffleAcademicBooks = useCallback(() => {
    setAcademicBooks(prevBooks => {
      const newBooks = [...prevBooks];
      for (let i = newBooks.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [newBooks[i], newBooks[j]] = [newBooks[j], newBooks[i]];
      }
      return newBooks;
    });
  }, []);

  const autoTestReuse = useCallback(async () => {
    message.info('开始单次复用测试...');
    console.log('autoTestReuse: Starting test...');

    domTrackStats.reset();
    setCurrentDomTrackStats({ created: 0, reused: 0, destroyed: 0 });

    setShowAcademicTestList(true);
    setAcademicBooks([]);
    await sleep(100);

    generateAcademicBooks(100);
    await sleep(1000);

    domTrackStats.reset();
    setCurrentDomTrackStats({ created: 0, reused: 0, destroyed: 0 });
    console.log('domTrackStats RESET before operation:', {
      created: domTrackStats.created,
      destroyed: domTrackStats.destroyed,
    });

    const startTime = performance.now();

    console.log(
      `autoTestReuse: Performing operation for keyType: ${keyType}...`
    );
    if (keyType === 'id') {
      shuffleAcademicBooks();
      console.log('Operation: shuffleAcademicBooks (for ID keys)');
    } else {
      const currentLength = academicBooks.length;
      setAcademicBooks([]);
      await sleep(2000);

      generateAcademicBooks(currentLength);
      console.log('Operation: replaceAllAcademicBooks (for Index/None keys)');
    }

    await sleep(5000);

    const totalTime = (performance.now() - startTime).toFixed(2);

    const createdCount = domTrackStats.created;
    const destroyedCount = domTrackStats.destroyed;
    const currentAcademicListLength = academicBooks.length;

    let reusedCount = 0;
    let reuseRatePercentage = '0.00';

    if (keyType === 'id') {
      reusedCount = currentAcademicListLength - destroyedCount;
      if (reusedCount < 0) reusedCount = 0;
      reuseRatePercentage = (
        currentAcademicListLength > 0
          ? (reusedCount / currentAcademicListLength) * 100
          : 0
      ).toFixed(2);
    } else {
      reusedCount = currentAcademicListLength - createdCount;
      if (reusedCount < 0) reusedCount = 0;
      reuseRatePercentage = (
        currentAcademicListLength > 0
          ? (reusedCount / currentAcademicListLength) * 100
          : 0
      ).toFixed(2);
    }

    setCurrentDomTrackStats({
      created: createdCount,
      reused: reusedCount,
      destroyed: destroyedCount,
    });

    setRenderTime(totalTime);

    console.log('autoTestReuse: Test finished. Stats:', {
      created: createdCount,
      reused: reusedCount,
      destroyed: destroyedCount,
      reuseRate: reuseRatePercentage,
      totalItems: currentAcademicListLength,
    });

    setShowAcademicTestList(false);
    setAcademicBooks([]);
    await sleep(500);

    message.success('单次复用测试完成！');
  }, [
    keyType,
    sleep,
    generateAcademicBooks,
    shuffleAcademicBooks,
    academicBooks.length,
  ]);

  const autoTestBatchAndExportExcel = useCallback(async () => {
    const testCases = [
      { name: 'ID作为Key', keyType: 'id' },
      { name: 'Index作为Key', keyType: 'index' },
      { name: '无Key', keyType: 'none' },
    ];

    const results = [];
    const operations = [
      { name: '生成100本', fn: () => generateBooks(100) },
      { name: '生成1000本', fn: () => generateBooks(1000) },
      { name: '打乱顺序', fn: () => shuffleList() },
      { name: '插入元素', fn: () => insertRandomBook() },
      { name: '删除元素', fn: () => deleteRandomBook() },
      { name: '替换所有', fn: () => replaceAllBooks() },
      { name: '尾部追加', fn: () => appendToEnd() },
      { name: '中间插入', fn: () => insertToMiddle() },
      { name: '局部更新', fn: () => partialUpdate() },
    ];

    for (const testCase of testCases) {
      message.info(`开始测试: ${testCase.name}`);
      setKeyType(testCase.keyType);
      await sleep(100);

      for (const operation of operations) {
        setBooks([]);
        await sleep(50);

        if (!operation.name.startsWith('生成')) {
          generateBooks(500);
          await sleep(50);
        }

        const renderDuration = await new Promise(resolve => {
          requestAnimationFrame(() => {
            performance.clearMarks();
            performance.clearMeasures();
            performance.mark('op-start');

            operation.fn();

            requestAnimationFrame(() => {
              performance.mark('op-end');
              performance.measure('op-duration', 'op-start', 'op-end');
              const measure = performance.getEntriesByName('op-duration')[0];
              const duration = measure ? measure.duration.toFixed(2) : '0.00';
              setRenderTime(duration);
              resolve(duration);
            });
          });
        });
        await sleep(200);

        results.push({
          测试类型: testCase.keyType,
          操作类型: operation.name,
          '渲染时间(ms)': renderDuration,
          列表项数量: books.length,
          测试时间: new Date().toLocaleString(),
        });
      }
    }

    const wb = XLSX.utils.book_new();
    const ws = XLSX.utils.json_to_sheet(results);
    ws['!cols'] = [
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 15 },
      { wch: 20 },
    ];
    XLSX.utils.book_append_sheet(wb, ws, '性能测试结果');
    XLSX.writeFile(wb, `performance_test_${Date.now()}.xlsx`);
    message.success('批量测试完成，数据已导出！');
  }, [
    sleep,
    generateBooks,
    shuffleList,
    insertRandomBook,
    deleteRandomBook,
    replaceAllBooks,
    appendToEnd,
    insertToMiddle,
    partialUpdate,
    books.length,
  ]);

  const exportReuseStatsToExcel = useCallback(() => {
    const stats = [
      {
        created: currentDomTrackStats.created,
        reused: currentDomTrackStats.reused,
        destroyed: currentDomTrackStats.destroyed,
        reuseRate: `${reuseRate()}%`,
        time: new Date().toLocaleString(),
      },
    ];

    const ws = XLSX.utils.json_to_sheet(stats);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, '复用统计');
    XLSX.writeFile(wb, `reuse-stats-${Date.now()}.xlsx`);
    message.success('统计数据已导出为Excel！');
  }, [currentDomTrackStats, reuseRate]);

  const columns = [
    {
      width: 50,
      render: (_, record) => (
        <Button
          type='text'
          className='expand-button'
          onClick={() => toggleExpand(record.id)}
          icon={
            <RightOutlined
              rotate={record.expanded ? 90 : 0}
              style={{ transition: 'transform 0.3s ease' }}
            />
          }
        />
      ),
    },
    {
      title: '书名',
      dataIndex: 'title',
      key: 'title',
      minWidth: 120,
      render: (text, record) => (
        <div className='book-info'>
          <span className='book-title'>{text}</span>
          {record.expanded && (
            <div className='book-detail'>
              <div className='detail-item'>
                <span className='label'>ISBN:</span>
                <span className='value'>{record.isbn || '暂无'}</span>
              </div>
              <div className='detail-item'>
                <span className='label'>出版社:</span>
                <span className='value'>{record.publisher || '暂无'}</span>
              </div>
              <div className='detail-item'>
                <span className='label'>出版日期:</span>
                <span className='value'>{record.publishDate || '暂无'}</span>
              </div>
              <div className='detail-item'>
                <span className='label'>简介:</span>
                <span className='value description'>
                  {record.description || '暂无简介'}
                </span>
              </div>
            </div>
          )}
        </div>
      ),
    },
    {
      title: '作者',
      dataIndex: 'author',
      key: 'author',
      width: 100,
    },
    {
      title: '出版社',
      dataIndex: 'publisher',
      key: 'publisher',
      width: 120,
    },
    {
      title: '出版日期',
      dataIndex: 'publishDate',
      key: 'publishDate',
      width: 100,
    },
    {
      title: 'ISBN',
      dataIndex: 'isbn',
      key: 'isbn',
      width: 140,
    },
    {
      title: '价格',
      dataIndex: 'price',
      key: 'price',
      width: 80,
    },
    {
      title: '评分',
      dataIndex: 'rating',
      key: 'rating',
      width: 80,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 80,
      render: status => (
        <Tag color={getStatusType(status)} size='small'>
          {status}
        </Tag>
      ),
    },
    {
      title: '操作',
      key: 'actions',
      width: 150,
      render: (_, record) => (
        <Space size='small'>
          <Button
            color='primary'
            variant='solid'
            size='small'
            onClick={() => viewBookDetail(record.id)}
          >
            查看
          </Button>
          <Button
            color='orange'
            variant='solid'
            size='small'
            onClick={() => editBook(record)}
          >
            编辑
          </Button>
        </Space>
      ),
    },
  ];

  return (
    <div
      className='book-list-container'
      style={{ padding: '20px', backgroundColor: '#fff' }}
    >
      <div className=''>
        <h1 className='page-heading'>图书目录管理</h1>
      </div>

      <Card
        className='performance-metrics w-full'
        style={{
          margin: '10px 0 20px',
          padding: '0px',
          background: '#f8f9fa',
          borderRadius: '4px',
        }}
        bordered={false}
      >
        <Title level={3} style={{ margin: '0 0 10px 0', color: '#409EFF' }}>
          性能指标
        </Title>
        <Row gutter={[10, 10]}>
          <Col xs={24} sm={12} md={8} lg={4}>
            <div className='metric-item'>
              <Text type='secondary' className='metric-label'>
                渲染时间：
              </Text>
              <Text
                strong
                style={{ color: '#e67e22' }}
                className='metric-value'
              >
                {renderTime || '0'} ms
              </Text>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8} lg={4}>
            <div className='metric-item'>
              <Text type='secondary' className='metric-label'>
                DOM创建数：
              </Text>
              <Text style={{ color: '#409EFF' }} className='metric-value'>
                {currentDomTrackStats.created || 0}
              </Text>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8} lg={4}>
            <div className='metric-item'>
              <Text type='secondary' className='metric-label'>
                DOM复用数：
              </Text>
              <Text style={{ color: '#67C23A' }} className='metric-value'>
                {currentDomTrackStats.reused || 0}
              </Text>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8} lg={4}>
            <div className='metric-item'>
              <Text type='secondary' className='metric-label'>
                DOM销毁数：
              </Text>
              <Text style={{ color: '#F56C6C' }} className='metric-value'>
                {currentDomTrackStats.destroyed || 0}
              </Text>
            </div>
          </Col>
          <Col xs={24} sm={12} md={8} lg={4}>
            <div className='metric-item'>
              <Text type='secondary' className='metric-label'>
                DOM复用率：
              </Text>
              <Text
                strong
                style={{ color: '#909399' }}
                className='metric-value'
              >
                {reuseRate()}%
              </Text>
            </div>
          </Col>
        </Row>
      </Card>
      <div className='id-key-btn' style={{ marginBottom: '10px' }}>
        <Space wrap>
          <Button
            type={keyType === 'id' ? 'primary' : 'default'}
            onClick={() => handleToggleType('id')}
          >
            ID作为Key
          </Button>
          <Button
            type={keyType === 'index' ? 'primary' : 'default'}
            onClick={() => handleToggleType('index')}
          >
            Index作为Key
          </Button>
          <Button
            type={keyType === 'none' ? 'primary' : 'default'}
            onClick={() => handleToggleType('none')}
          >
            无Key
          </Button>
          <Button color='primary' variant='solid' onClick={bulkGenerate}>
            批量生成1000项
          </Button>
          <Button color='orange' variant='solid' onClick={addItem}>
            添加项
          </Button>
          <Button color='danger' variant='solid' onClick={removeItem}>
            删除项
          </Button>
          <Button color='green' variant='solid' onClick={shuffleList}>
            打乱顺序
          </Button>
          <Button color='primary' variant='solid' onClick={insertRandomBook}>
            插入元素
          </Button>
          <Button color='orange' variant='solid' onClick={deleteRandomBook}>
            删除元素
          </Button>
          <Button color='danger' variant='solid' onClick={replaceAllBooks}>
            替换所有
          </Button>
          <Button color='green' variant='solid' onClick={appendToEnd}>
            尾部追加
          </Button>
          <Button color='primary' variant='solid' onClick={stepInsert}>
            步步插入
          </Button>
          <Button color='orange' variant='solid' onClick={insertToMiddle}>
            中间插入
          </Button>
          <Button color='danger' variant='solid' onClick={partialUpdate}>
            局部更新
          </Button>
          <Button color='green' variant='solid' onClick={autoTestReuse}>
            自动测试复用（单次）
          </Button>
          <Button
            color='primary'
            variant='solid'
            onClick={autoTestBatchAndExportExcel}
          >
            批量测试并导出Excel
          </Button>
          <Button
            color='orange'
            variant='solid'
            onClick={exportReuseStatsToExcel}
          >
            导出Excel（当前）
          </Button>
        </Space>
      </div>

      {renderTime && (
        <div
          style={{ marginBottom: '12px', color: '#e67e22', fontWeight: 'bold' }}
        >
          本次渲染耗时：{renderTime} ms
          <br />
          节点创建：{currentDomTrackStats.created}，复用：
          {currentDomTrackStats.reused}，销毁：{currentDomTrackStats.destroyed}
          ，复用率：{reuseRate()}%
        </div>
      )}

      {/* Used for academic data testing to accurately capture created and destroyed */}
      {showAcademicTestList && (
        <div
          className='academic-test-list'
          style={{
            border: '1px dashed #ccc',
            padding: '10px',
            marginTop: '20px',
          }}
        >
          {academicBooks.map((book, index) => (
            <DomTracker
              key={keyType === 'id' ? book.id : index}
              id={keyType === 'id' ? book.id : index}
            >
              <span
                data-id={book.id}
                style={{
                  padding: '5px',
                  border: '1px solid #eee',
                  margin: '2px',
                  display: 'inline-block',
                }}
              >
                {book.title}
              </span>
            </DomTracker>
          ))}
        </div>
      )}

      <Card
        className='module-info'
        style={{
          backgroundColor: '#f8f9fa',
          padding: '0px',
          borderRadius: '4px',
          marginBottom: '20px',
        }}
        bordered={false}
      >
        <div
          className='info-icon'
          style={{ display: 'flex', alignItems: 'center', marginBottom: '8px' }}
        >
          <InfoCircleOutlined
            style={{ color: '#909399', marginRight: '5px' }}
          />
          <Text strong style={{ color: '#606266', fontSize: '14px' }}>
            模块说明
          </Text>
        </div>
        <Text
          style={{
            color: '#606266',
            fontSize: '12px',
            lineHeight: '1.5',
            margin: 0,
          }}
        >
          图书目录管理模块用于管理图书馆的所有图书信息，包括基本信息、库存状态等。支持展开查看详细信息，方便管理员快速了解图书详情。
        </Text>
      </Card>

      <div className='book-table'>
        <Table
          columns={columns}
          dataSource={books}
          rowKey={getKey}
          pagination={false}
          size='middle'
          scroll={{ x: 'max-content' }}
        />
      </div>
    </div>
  );
};

export default BookList;
